home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16_Src.lha / Python16_Source / Modules / _sre.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-09-13  |  61.1 KB  |  2,305 lines

  1. /*
  2.  * Secret Labs' Regular Expression Engine
  3.  *
  4.  * regular expression matching engine
  5.  *
  6.  * partial history:
  7.  * 99-10-24 fl  created (based on existing template matcher code)
  8.  * 00-03-06 fl  first alpha, sort of (0.5)
  9.  * 00-06-30 fl  added fast search optimization (0.9.3)
  10.  * 00-06-30 fl  added assert (lookahead) primitives, etc (0.9.4)
  11.  * 00-07-02 fl  added charset optimizations, etc (0.9.5)
  12.  * 00-07-03 fl  store code in pattern object, lookbehind, etc
  13.  * 00-07-08 fl  added regs attribute
  14.  * 00-07-21 fl  reset lastindex in scanner methods (0.9.6)
  15.  * 00-08-01 fl  fixes for 1.6b1 (0.9.8)
  16.  * 00-08-03 fl  added recursion limit
  17.  * 00-08-07 fl  use PyOS_CheckStack() if available
  18.  * 00-08-08 fl  changed findall to return empty strings instead of None
  19.  * 00-08-27 fl  properly propagate memory errors
  20.  * 00-09-02 fl  return -1 instead of None for start/end/span
  21.  *
  22.  * Copyright (c) 1997-2000 by Secret Labs AB.  All rights reserved.
  23.  *
  24.  * This version of the SRE library can be redistributed under CNRI's
  25.  * Python 1.6 license.  For any other use, please contact Secret Labs
  26.  * AB (info@pythonware.com).
  27.  *
  28.  * Portions of this engine have been developed in cooperation with
  29.  * CNRI.  Hewlett-Packard provided funding for 1.6 integration and
  30.  * other compatibility work.
  31.  */
  32.  
  33. #ifndef SRE_RECURSIVE
  34.  
  35. char copyright[] = " SRE 0.9.8 Copyright (c) 1997-2000 by Secret Labs AB ";
  36.  
  37. #include "Python.h"
  38.  
  39. #include "sre.h"
  40.  
  41. #if defined(HAVE_LIMITS_H)
  42. #include <limits.h>
  43. #else
  44. #define INT_MAX 2147483647
  45. #endif
  46.  
  47. #include <ctype.h>
  48.  
  49. /* name of this module, minus the leading underscore */
  50. #define MODULE "sre"
  51.  
  52. /* defining this one enables tracing */
  53. #undef VERBOSE
  54.  
  55. #if PY_VERSION_HEX >= 0x01060000
  56. /* defining this enables unicode support (default under 1.6a1 and later) */
  57. #define HAVE_UNICODE
  58. #endif
  59.  
  60. /* -------------------------------------------------------------------- */
  61. /* optional features */
  62.  
  63. /* prevent run-away recursion (bad patterns on long strings) */
  64.  
  65. #if !defined(USE_STACKCHECK)
  66. #if defined(MS_WIN64) || defined(__LP64__) || defined(_LP64)
  67. /* require smaller recursion limit for a number of 64-bit platforms:
  68.    Win64 (MS_WIN64), Linux64 (__LP64__), Monterey (64-bit AIX) (_LP64) */
  69. /* FIXME: maybe the limit should be 40000 / sizeof(void*) ? */
  70. #define USE_RECURSION_LIMIT 7500
  71. #else
  72. #define USE_RECURSION_LIMIT 10000
  73. #endif
  74. #endif
  75.  
  76. /* enables fast searching */
  77. #define USE_FAST_SEARCH
  78.  
  79. /* enables aggressive inlining (always on for Visual C) */
  80. #undef USE_INLINE
  81.  
  82. /* -------------------------------------------------------------------- */
  83.  
  84. #if defined(_MSC_VER)
  85. #pragma optimize("agtw", on) /* doesn't seem to make much difference... */
  86. #pragma warning(disable: 4710) /* who cares if functions are not inlined ;-) */
  87. /* fastest possible local call under MSVC */
  88. #define LOCAL(type) static __inline type __fastcall
  89. #elif defined(USE_INLINE)
  90. #define LOCAL(type) static inline type
  91. #else
  92. #define LOCAL(type) static type
  93. #endif
  94.  
  95. /* error codes */
  96. #define SRE_ERROR_ILLEGAL -1 /* illegal opcode */
  97. #define SRE_ERROR_STATE -2 /* illegal state */
  98. #define SRE_ERROR_RECURSION_LIMIT -3 /* runaway recursion */
  99. #define SRE_ERROR_MEMORY -9 /* out of memory */
  100.  
  101. #if defined(VERBOSE)
  102. #define TRACE(v) printf v
  103. #else
  104. #define TRACE(v)
  105. #endif
  106.  
  107. /* -------------------------------------------------------------------- */
  108. /* search engine state */
  109.  
  110. /* default character predicates (run sre_chars.py to regenerate tables) */
  111.  
  112. #define SRE_DIGIT_MASK 1
  113. #define SRE_SPACE_MASK 2
  114. #define SRE_LINEBREAK_MASK 4
  115. #define SRE_ALNUM_MASK 8
  116. #define SRE_WORD_MASK 16
  117.  
  118. static char sre_char_info[128] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 6, 2,
  119. 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0,
  120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 25, 25, 25, 25, 25, 25, 25,
  121. 25, 25, 0, 0, 0, 0, 0, 0, 0, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  122. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0,
  123. 0, 0, 16, 0, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  124. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0, 0, 0, 0 };
  125.  
  126. static char sre_char_lower[128] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
  127. 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
  128. 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
  129. 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
  130. 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107,
  131. 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  132. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
  133. 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  134. 120, 121, 122, 123, 124, 125, 126, 127 };
  135.  
  136. static unsigned int sre_lower(unsigned int ch)
  137. {
  138.     return ((ch) < 128 ? sre_char_lower[ch] : ch);
  139. }
  140.  
  141. #define SRE_IS_DIGIT(ch)\
  142.     ((ch) < 128 ? (sre_char_info[(ch)] & SRE_DIGIT_MASK) : 0)
  143. #define SRE_IS_SPACE(ch)\
  144.     ((ch) < 128 ? (sre_char_info[(ch)] & SRE_SPACE_MASK) : 0)
  145. #define SRE_IS_LINEBREAK(ch)\
  146.     ((ch) < 128 ? (sre_char_info[(ch)] & SRE_LINEBREAK_MASK) : 0)
  147. #define SRE_IS_ALNUM(ch)\
  148.     ((ch) < 128 ? (sre_char_info[(ch)] & SRE_ALNUM_MASK) : 0)
  149. #define SRE_IS_WORD(ch)\
  150.     ((ch) < 128 ? (sre_char_info[(ch)] & SRE_WORD_MASK) : 0)
  151.  
  152. /* locale-specific character predicates */
  153.  
  154. static unsigned int sre_lower_locale(unsigned int ch)
  155. {
  156.     return ((ch) < 256 ? tolower((ch)) : ch);
  157. }
  158. #define SRE_LOC_IS_DIGIT(ch) ((ch) < 256 ? isdigit((ch)) : 0)
  159. #define SRE_LOC_IS_SPACE(ch) ((ch) < 256 ? isspace((ch)) : 0)
  160. #define SRE_LOC_IS_LINEBREAK(ch) ((ch) == '\n')
  161. #define SRE_LOC_IS_ALNUM(ch) ((ch) < 256 ? isalnum((ch)) : 0)
  162. #define SRE_LOC_IS_WORD(ch) (SRE_LOC_IS_ALNUM((ch)) || (ch) == '_')
  163.  
  164. /* unicode-specific character predicates */
  165.  
  166. #if defined(HAVE_UNICODE)
  167. static unsigned int sre_lower_unicode(unsigned int ch)
  168. {
  169.     return (unsigned int) Py_UNICODE_TOLOWER((Py_UNICODE)(ch));
  170. }
  171. #define SRE_UNI_IS_DIGIT(ch) Py_UNICODE_ISDIGIT((Py_UNICODE)(ch))
  172. #define SRE_UNI_IS_SPACE(ch) Py_UNICODE_ISSPACE((Py_UNICODE)(ch))
  173. #define SRE_UNI_IS_LINEBREAK(ch) Py_UNICODE_ISLINEBREAK((Py_UNICODE)(ch))
  174. #define SRE_UNI_IS_ALNUM(ch) Py_UNICODE_ISALNUM((Py_UNICODE)(ch))
  175. #define SRE_UNI_IS_WORD(ch) (SRE_UNI_IS_ALNUM((ch)) || (ch) == '_')
  176. #endif
  177.  
  178. LOCAL(int)
  179. sre_category(SRE_CODE category, unsigned int ch)
  180. {
  181.     switch (category) {
  182.  
  183.     case SRE_CATEGORY_DIGIT:
  184.         return SRE_IS_DIGIT(ch);
  185.     case SRE_CATEGORY_NOT_DIGIT:
  186.         return !SRE_IS_DIGIT(ch);
  187.     case SRE_CATEGORY_SPACE:
  188.         return SRE_IS_SPACE(ch);
  189.     case SRE_CATEGORY_NOT_SPACE:
  190.         return !SRE_IS_SPACE(ch);
  191.     case SRE_CATEGORY_WORD:
  192.         return SRE_IS_WORD(ch);
  193.     case SRE_CATEGORY_NOT_WORD:
  194.         return !SRE_IS_WORD(ch);
  195.     case SRE_CATEGORY_LINEBREAK:
  196.         return SRE_IS_LINEBREAK(ch);
  197.     case SRE_CATEGORY_NOT_LINEBREAK:
  198.         return !SRE_IS_LINEBREAK(ch);
  199.  
  200.     case SRE_CATEGORY_LOC_WORD:
  201.         return SRE_LOC_IS_WORD(ch);
  202.     case SRE_CATEGORY_LOC_NOT_WORD:
  203.         return !SRE_LOC_IS_WORD(ch);
  204.  
  205. #if defined(HAVE_UNICODE)
  206.     case SRE_CATEGORY_UNI_DIGIT:
  207.         return SRE_UNI_IS_DIGIT(ch);
  208.     case SRE_CATEGORY_UNI_NOT_DIGIT:
  209.         return !SRE_UNI_IS_DIGIT(ch);
  210.     case SRE_CATEGORY_UNI_SPACE:
  211.         return SRE_UNI_IS_SPACE(ch);
  212.     case SRE_CATEGORY_UNI_NOT_SPACE:
  213.         return !SRE_UNI_IS_SPACE(ch);
  214.     case SRE_CATEGORY_UNI_WORD:
  215.         return SRE_UNI_IS_WORD(ch);
  216.     case SRE_CATEGORY_UNI_NOT_WORD:
  217.         return !SRE_UNI_IS_WORD(ch);
  218.     case SRE_CATEGORY_UNI_LINEBREAK:
  219.         return SRE_UNI_IS_LINEBREAK(ch);
  220.     case SRE_CATEGORY_UNI_NOT_LINEBREAK:
  221.         return !SRE_UNI_IS_LINEBREAK(ch);
  222. #endif
  223.     }
  224.     return 0;
  225. }
  226.  
  227. /* helpers */
  228.  
  229. static void
  230. mark_fini(SRE_STATE* state)
  231. {
  232.     if (state->mark_stack) {
  233.         free(state->mark_stack);
  234.         state->mark_stack = NULL;
  235.     }
  236.     state->mark_stack_size = state->mark_stack_base = 0;
  237. }
  238.  
  239. static int
  240. mark_save(SRE_STATE* state, int lo, int hi)
  241. {
  242.     void* stack;
  243.     int size;
  244.     int minsize, newsize;
  245.  
  246.     if (hi <= lo)
  247.         return 0;
  248.  
  249.     size = (hi - lo) + 1;
  250.  
  251.     newsize = state->mark_stack_size;
  252.     minsize = state->mark_stack_base + size;
  253.  
  254.     if (newsize < minsize) {
  255.         /* create new stack */
  256.         if (!newsize) {
  257.             newsize = 512;
  258.             if (newsize < minsize)
  259.                 newsize = minsize;
  260.             TRACE(("allocate stack %d\n", newsize));
  261.             stack = malloc(sizeof(void*) * newsize);
  262.         } else {
  263.             /* grow the stack */
  264.             while (newsize < minsize)
  265.                 newsize += newsize;
  266.             TRACE(("grow stack to %d\n", newsize));
  267.             stack = realloc(state->mark_stack, sizeof(void*) * newsize);
  268.         }
  269.         if (!stack) {
  270.             mark_fini(state);
  271.             return SRE_ERROR_MEMORY;
  272.         }
  273.         state->mark_stack = stack;
  274.         state->mark_stack_size = newsize;
  275.     }
  276.  
  277.     TRACE(("copy %d:%d to %d (%d)\n", lo, hi, state->mark_stack_base, size));
  278.  
  279.     memcpy(state->mark_stack + state->mark_stack_base, state->mark + lo,
  280.            size * sizeof(void*));
  281.  
  282.     state->mark_stack_base += size;
  283.  
  284.     return 0;
  285. }
  286.  
  287. static int
  288. mark_restore(SRE_STATE* state, int lo, int hi)
  289. {
  290.     int size;
  291.  
  292.     if (hi <= lo)
  293.         return 0;
  294.  
  295.     size = (hi - lo) + 1;
  296.  
  297.     state->mark_stack_base -= size;
  298.  
  299.     TRACE(("copy %d:%d from %d\n", lo, hi, state->mark_stack_base));
  300.  
  301.     memcpy(state->mark + lo, state->mark_stack + state->mark_stack_base,
  302.            size * sizeof(void*));
  303.  
  304.     return 0;
  305. }
  306.  
  307. /* generate 8-bit version */
  308.  
  309. #define SRE_CHAR unsigned char
  310. #define SRE_AT sre_at
  311. #define SRE_COUNT sre_count
  312. #define SRE_CHARSET sre_charset
  313. #define SRE_INFO sre_info
  314. #define SRE_MATCH sre_match
  315. #define SRE_SEARCH sre_search
  316.  
  317. #if defined(HAVE_UNICODE)
  318.  
  319. #define SRE_RECURSIVE
  320. #include "_sre.c"
  321. #undef SRE_RECURSIVE
  322.  
  323. #undef SRE_SEARCH
  324. #undef SRE_MATCH
  325. #undef SRE_INFO
  326. #undef SRE_CHARSET
  327. #undef SRE_COUNT
  328. #undef SRE_AT
  329. #undef SRE_CHAR
  330.  
  331. /* generate 16-bit unicode version */
  332.  
  333. #define SRE_CHAR Py_UNICODE
  334. #define SRE_AT sre_uat
  335. #define SRE_COUNT sre_ucount
  336. #define SRE_CHARSET sre_ucharset
  337. #define SRE_INFO sre_uinfo
  338. #define SRE_MATCH sre_umatch
  339. #define SRE_SEARCH sre_usearch
  340. #endif
  341.  
  342. #endif /* SRE_RECURSIVE */
  343.  
  344. /* -------------------------------------------------------------------- */
  345. /* String matching engine */
  346.  
  347. /* the following section is compiled twice, with different character
  348.    settings */
  349.  
  350. LOCAL(int)
  351. SRE_AT(SRE_STATE* state, SRE_CHAR* ptr, SRE_CODE at)
  352. {
  353.     /* check if pointer is at given position */
  354.  
  355.     int this, that;
  356.  
  357.     switch (at) {
  358.  
  359.     case SRE_AT_BEGINNING:
  360.         return ((void*) ptr == state->beginning);
  361.  
  362.     case SRE_AT_BEGINNING_LINE:
  363.         return ((void*) ptr == state->beginning ||
  364.                 SRE_IS_LINEBREAK((int) ptr[-1]));
  365.  
  366.     case SRE_AT_END:
  367.         return (((void*) (ptr+1) == state->end &&
  368.                  SRE_IS_LINEBREAK((int) ptr[0])) ||
  369.                 ((void*) ptr == state->end));
  370.  
  371.     case SRE_AT_END_LINE:
  372.         return ((void*) ptr == state->end ||
  373.                 SRE_IS_LINEBREAK((int) ptr[0]));
  374.  
  375.     case SRE_AT_BOUNDARY:
  376.         if (state->beginning == state->end)
  377.             return 0;
  378.         that = ((void*) ptr > state->beginning) ?
  379.             SRE_IS_WORD((int) ptr[-1]) : 0;
  380.         this = ((void*) ptr < state->end) ?
  381.             SRE_IS_WORD((int) ptr[0]) : 0;
  382.         return this != that;
  383.  
  384.     case SRE_AT_NON_BOUNDARY:
  385.         if (state->beginning == state->end)
  386.             return 0;
  387.         that = ((void*) ptr > state->beginning) ?
  388.             SRE_IS_WORD((int) ptr[-1]) : 0;
  389.         this = ((void*) ptr < state->end) ?
  390.             SRE_IS_WORD((int) ptr[0]) : 0;
  391.         return this == that;
  392.     }
  393.  
  394.     return 0;
  395. }
  396.  
  397. LOCAL(int)
  398. SRE_CHARSET(SRE_CODE* set, SRE_CODE ch)
  399. {
  400.     /* check if character is a member of the given set */
  401.  
  402.     int ok = 1;
  403.  
  404.     for (;;) {
  405.         switch (*set++) {
  406.  
  407.         case SRE_OP_LITERAL:
  408.             /* <LITERAL> <code> */
  409.             if (ch == set[0])
  410.                 return ok;
  411.             set++;
  412.             break;
  413.  
  414.         case SRE_OP_RANGE:
  415.             /* <RANGE> <lower> <upper> */
  416.             if (set[0] <= ch && ch <= set[1])
  417.                 return ok;
  418.             set += 2;
  419.             break;
  420.  
  421.         case SRE_OP_CHARSET:
  422.             /* <CHARSET> <bitmap> (16 bits per code word) */
  423.             if (ch < 256 && (set[ch >> 4] & (1 << (ch & 15))))
  424.                 return ok;
  425.             set += 16;
  426.             break;
  427.  
  428.         case SRE_OP_CATEGORY:
  429.             /* <CATEGORY> <code> */
  430.             if (sre_category(set[0], (int) ch))
  431.                 return ok;
  432.             set += 1;
  433.             break;
  434.  
  435.         case SRE_OP_NEGATE:
  436.             ok = !ok;
  437.             break;
  438.  
  439.         case SRE_OP_FAILURE:
  440.             return !ok;
  441.  
  442.         default:
  443.             /* internal error -- there's not much we can do about it
  444.                here, so let's just pretend it didn't match... */
  445.             return 0;
  446.         }
  447.     }
  448. }
  449.  
  450. LOCAL(int) SRE_MATCH(SRE_STATE* state, SRE_CODE* pattern, int level);
  451.  
  452. LOCAL(int)
  453. SRE_COUNT(SRE_STATE* state, SRE_CODE* pattern, int maxcount, int level)
  454. {
  455.     SRE_CODE chr;
  456.     SRE_CHAR* ptr = state->ptr;
  457.     SRE_CHAR* end = state->end;
  458.     int i;
  459.  
  460.     /* adjust end */
  461.     if (maxcount < end - ptr && maxcount != 65535)
  462.         end = ptr + maxcount;
  463.  
  464.     switch (pattern[0]) {
  465.  
  466.     case SRE_OP_ANY:
  467.         /* repeated dot wildcard. */
  468.         TRACE(("|%p|%p|COUNT ANY\n", pattern, ptr));
  469.         while (ptr < end && !SRE_IS_LINEBREAK(*ptr))
  470.             ptr++;
  471.         break;
  472.  
  473.     case SRE_OP_ANY_ALL:
  474.         /* repeated dot wildcare.  skip to the end of the target
  475.            string, and backtrack from there */
  476.         TRACE(("|%p|%p|COUNT ANY_ALL\n", pattern, ptr));
  477.         ptr = end;
  478.         break;
  479.  
  480.     case SRE_OP_LITERAL:
  481.         /* repeated literal */
  482.         chr = pattern[1];
  483.         TRACE(("|%p|%p|COUNT LITERAL %d\n", pattern, ptr, chr));
  484.         while (ptr < end && (SRE_CODE) *ptr == chr)
  485.             ptr++;
  486.         break;
  487.  
  488.     case SRE_OP_LITERAL_IGNORE:
  489.         /* repeated literal */
  490.         chr = pattern[1];
  491.         TRACE(("|%p|%p|COUNT LITERAL_IGNORE %d\n", pattern, ptr, chr));
  492.         while (ptr < end && (SRE_CODE) state->lower(*ptr) == chr)
  493.             ptr++;
  494.         break;
  495.  
  496.     case SRE_OP_NOT_LITERAL:
  497.         /* repeated non-literal */
  498.         chr = pattern[1];
  499.         TRACE(("|%p|%p|COUNT NOT_LITERAL %d\n", pattern, ptr, chr));
  500.         while (ptr < end && (SRE_CODE) *ptr != chr)
  501.             ptr++;
  502.         break;
  503.                 
  504.     case SRE_OP_NOT_LITERAL_IGNORE:
  505.         /* repeated non-literal */
  506.         chr = pattern[1];
  507.         TRACE(("|%p|%p|COUNT NOT_LITERAL_IGNORE %d\n", pattern, ptr, chr));
  508.         while (ptr < end && (SRE_CODE) state->lower(*ptr) != chr)
  509.             ptr++;
  510.         break;
  511.  
  512.     case SRE_OP_IN:
  513.         /* repeated set */
  514.         TRACE(("|%p|%p|COUNT IN\n", pattern, ptr));
  515.         while (ptr < end && SRE_CHARSET(pattern + 2, *ptr))
  516.             ptr++;
  517.         break;
  518.  
  519.     default:
  520.         /* repeated single character pattern */
  521.         TRACE(("|%p|%p|COUNT SUBPATTERN\n", pattern, ptr));
  522.         while ((SRE_CHAR*) state->ptr < end) {
  523.             i = SRE_MATCH(state, pattern, level);
  524.             if (i < 0)
  525.                 return i;
  526.             if (!i)
  527.                 break;
  528.         }
  529.         TRACE(("|%p|%p|COUNT %d\n", pattern, ptr,
  530.                (SRE_CHAR*) state->ptr - ptr));
  531.         return (SRE_CHAR*) state->ptr - ptr;
  532.     }
  533.  
  534.     TRACE(("|%p|%p|COUNT %d\n", pattern, ptr, ptr - (SRE_CHAR*) state->ptr));
  535.     return ptr - (SRE_CHAR*) state->ptr;
  536. }
  537.  
  538. #if 0 /* not used in this release */
  539. LOCAL(int)
  540. SRE_INFO(SRE_STATE* state, SRE_CODE* pattern)
  541. {
  542.     /* check if an SRE_OP_INFO block matches at the current position.
  543.        returns the number of SRE_CODE objects to skip if successful, 0
  544.        if no match */
  545.  
  546.     SRE_CHAR* end = state->end;
  547.     SRE_CHAR* ptr = state->ptr;
  548.     int i;
  549.  
  550.     /* check minimal length */
  551.     if (pattern[3] && (end - ptr) < pattern[3])
  552.         return 0;
  553.  
  554.     /* check known prefix */
  555.     if (pattern[2] & SRE_INFO_PREFIX && pattern[5] > 1) {
  556.         /* <length> <skip> <prefix data> <overlap data> */
  557.         for (i = 0; i < pattern[5]; i++)
  558.             if ((SRE_CODE) ptr[i] != pattern[7 + i])
  559.                 return 0;
  560.         return pattern[0] + 2 * pattern[6];
  561.     }
  562.     return pattern[0];
  563. }
  564. #endif
  565.  
  566. LOCAL(int)
  567. SRE_MATCH(SRE_STATE* state, SRE_CODE* pattern, int level)
  568. {
  569.     /* check if string matches the given pattern.  returns <0 for
  570.        error, 0 for failure, and 1 for success */
  571.  
  572.     SRE_CHAR* end = state->end;
  573.     SRE_CHAR* ptr = state->ptr;
  574.     int i, count;
  575.     SRE_REPEAT* rp;
  576.     int lastmark;
  577.     SRE_CODE chr;
  578.  
  579.     SRE_REPEAT rep; /* FIXME: <fl> allocate in STATE instead */
  580.  
  581.     TRACE(("|%p|%p|ENTER %d\n", pattern, ptr, level));
  582.  
  583. #if defined(USE_STACKCHECK)
  584.     if (level % 10 == 0 && PyOS_CheckStack())
  585.         return SRE_ERROR_RECURSION_LIMIT;
  586. #endif
  587.  
  588. #if defined(USE_RECURSION_LIMIT)
  589.     if (level > USE_RECURSION_LIMIT)
  590.         return SRE_ERROR_RECURSION_LIMIT;
  591. #endif
  592.  
  593.     if (pattern[0] == SRE_OP_INFO) {
  594.         /* optimization info block */
  595.         /* <INFO> <1=skip> <2=flags> <3=min> ... */
  596.         if (pattern[3] && (end - ptr) < pattern[3]) {
  597.             TRACE(("reject (got %d chars, need %d)\n",
  598.                    (end - ptr), pattern[3]));
  599.             return 0;
  600.         }
  601.         pattern += pattern[1] + 1;
  602.     }
  603.  
  604.     for (;;) {
  605.  
  606.         switch (*pattern++) {
  607.  
  608.         case SRE_OP_FAILURE:
  609.             /* immediate failure */
  610.             TRACE(("|%p|%p|FAILURE\n", pattern, ptr));
  611.             return 0;
  612.  
  613.         case SRE_OP_SUCCESS:
  614.             /* end of pattern */
  615.             TRACE(("|%p|%p|SUCCESS\n", pattern, ptr));
  616.             state->ptr = ptr;
  617.             return 1;
  618.  
  619.         case SRE_OP_AT:
  620.             /* match at given position */
  621.             /* <AT> <code> */
  622.             TRACE(("|%p|%p|AT %d\n", pattern, ptr, *pattern));
  623.             if (!SRE_AT(state, ptr, *pattern))
  624.                 return 0;
  625.             pattern++;
  626.             break;
  627.  
  628.         case SRE_OP_CATEGORY:
  629.             /* match at given category */
  630.             /* <CATEGORY> <code> */
  631.             TRACE(("|%p|%p|CATEGORY %d\n", pattern, ptr, *pattern));
  632.             if (ptr >= end || !sre_category(pattern[0], ptr[0]))
  633.                 return 0;
  634.             pattern++;
  635.             ptr++;
  636.             break;
  637.  
  638.         case SRE_OP_LITERAL:
  639.             /* match literal string */
  640.             /* <LITERAL> <code> */
  641.             TRACE(("|%p|%p|LITERAL %d\n", pattern, ptr, *pattern));
  642.             if (ptr >= end || (SRE_CODE) ptr[0] != pattern[0])
  643.                 return 0;
  644.             pattern++;
  645.             ptr++;
  646.             break;
  647.  
  648.         case SRE_OP_NOT_LITERAL:
  649.             /* match anything that is not literal character */
  650.             /* <NOT_LITERAL> <code> */
  651.             TRACE(("|%p|%p|NOT_LITERAL %d\n", pattern, ptr, *pattern));
  652.             if (ptr >= end || (SRE_CODE) ptr[0] == pattern[0])
  653.                 return 0;
  654.             pattern++;
  655.             ptr++;
  656.             break;
  657.  
  658.         case SRE_OP_ANY:
  659.             /* match anything (except a newline) */
  660.             /* <ANY> */
  661.             TRACE(("|%p|%p|ANY\n", pattern, ptr));
  662.             if (ptr >= end || SRE_IS_LINEBREAK(ptr[0]))
  663.                 return 0;
  664.             ptr++;
  665.             break;
  666.  
  667.         case SRE_OP_ANY_ALL:
  668.             /* match anything */
  669.             /* <ANY_ALL> */
  670.             TRACE(("|%p|%p|ANY_ALL\n", pattern, ptr));
  671.             if (ptr >= end)
  672.                 return 0;
  673.             ptr++;
  674.             break;
  675.  
  676.         case SRE_OP_IN:
  677.             /* match set member (or non_member) */
  678.             /* <IN> <skip> <set> */
  679.             TRACE(("|%p|%p|IN\n", pattern, ptr));
  680.             if (ptr >= end || !SRE_CHARSET(pattern + 1, *ptr))
  681.                 return 0;
  682.             pattern += pattern[0];
  683.             ptr++;
  684.             break;
  685.  
  686.         case SRE_OP_GROUPREF:
  687.             /* match backreference */
  688.             TRACE(("|%p|%p|GROUPREF %d\n", pattern, ptr, pattern[0]));
  689.             i = pattern[0];
  690.             {
  691.                 SRE_CHAR* p = (SRE_CHAR*) state->mark[i+i];
  692.                 SRE_CHAR* e = (SRE_CHAR*) state->mark[i+i+1];
  693.                 if (!p || !e || e < p)
  694.                     return 0;
  695.                 while (p < e) {
  696.                     if (ptr >= end || *ptr != *p)
  697.                         return 0;
  698.                     p++; ptr++;
  699.                 }
  700.             }
  701.             pattern++;
  702.             break;
  703.  
  704.         case SRE_OP_GROUPREF_IGNORE:
  705.             /* match backreference */
  706.             TRACE(("|%p|%p|GROUPREF_IGNORE %d\n", pattern, ptr, pattern[0]));
  707.             i = pattern[0];
  708.             {
  709.                 SRE_CHAR* p = (SRE_CHAR*) state->mark[i+i];
  710.                 SRE_CHAR* e = (SRE_CHAR*) state->mark[i+i+1];
  711.                 if (!p || !e || e < p)
  712.                     return 0;
  713.                 while (p < e) {
  714.                     if (ptr >= end ||
  715.                         state->lower(*ptr) != state->lower(*p))
  716.                         return 0;
  717.                     p++; ptr++;
  718.                 }
  719.             }
  720.             pattern++;
  721.             break;
  722.  
  723.         case SRE_OP_LITERAL_IGNORE:
  724.             TRACE(("|%p|%p|LITERAL_IGNORE %d\n", pattern, ptr, pattern[0]));
  725.             if (ptr >= end ||
  726.                 state->lower(*ptr) != state->lower(*pattern))
  727.                 return 0;
  728.             pattern++;
  729.             ptr++;
  730.             break;
  731.  
  732.         case SRE_OP_NOT_LITERAL_IGNORE:
  733.             TRACE(("|%p|%p|NOT_LITERAL_IGNORE %d\n", pattern, ptr, *pattern));
  734.             if (ptr >= end ||
  735.                 state->lower(*ptr) == state->lower(*pattern))
  736.                 return 0;
  737.             pattern++;
  738.             ptr++;
  739.             break;
  740.  
  741.         case SRE_OP_IN_IGNORE:
  742.             TRACE(("|%p|%p|IN_IGNORE\n", pattern, ptr));
  743.             if (ptr >= end
  744.                 || !SRE_CHARSET(pattern + 1, (SRE_CODE) state->lower(*ptr)))
  745.                 return 0;
  746.             pattern += pattern[0];
  747.             ptr++;
  748.             break;
  749.  
  750.         case SRE_OP_MARK:
  751.             /* set mark */
  752.             /* <MARK> <gid> */
  753.             TRACE(("|%p|%p|MARK %d\n", pattern, ptr, pattern[0]));
  754.             i = pattern[0];
  755.             if (i & 1)
  756.                 state->lastindex = i/2 + 1;
  757.             if (i > state->lastmark)
  758.                 state->lastmark = i;
  759.             state->mark[i] = ptr;
  760.             pattern++;
  761.             break;
  762.  
  763.         case SRE_OP_JUMP:
  764.         case SRE_OP_INFO:
  765.             /* jump forward */
  766.             /* <JUMP> <offset> */
  767.             TRACE(("|%p|%p|JUMP %d\n", pattern, ptr, pattern[0]));
  768.             pattern += pattern[0];
  769.             break;
  770.  
  771.         case SRE_OP_ASSERT:
  772.             /* assert subpattern */
  773.             /* <ASSERT> <skip> <back> <pattern> */
  774.             TRACE(("|%p|%p|ASSERT %d\n", pattern, ptr, pattern[1]));
  775.             state->ptr = ptr - pattern[1];
  776.             if (state->ptr < state->beginning)
  777.                 return 0;
  778.             i = SRE_MATCH(state, pattern + 2, level + 1);
  779.             if (i <= 0)
  780.                 return i;
  781.             if (pattern[1] > 0 && state->ptr != ptr)
  782.                 return SRE_ERROR_STATE;
  783.             pattern += pattern[0];
  784.             break;
  785.  
  786.         case SRE_OP_ASSERT_NOT:
  787.             /* assert not subpattern */
  788.             /* <ASSERT_NOT> <skip> <back> <pattern> */
  789.             TRACE(("|%p|%p|ASSERT_NOT %d\n", pattern, ptr, pattern[1]));
  790.             state->ptr = ptr - pattern[1];
  791.             if (state->ptr < state->beginning)
  792.                 return 0;
  793.             i = SRE_MATCH(state, pattern + 2, level + 1);
  794.             if (i < 0)
  795.                 return i;
  796.             if (i)
  797.                 return 0;
  798.             if (pattern[1] > 0 && state->ptr != ptr)
  799.                 return SRE_ERROR_STATE;
  800.             pattern += pattern[0];
  801.             break;
  802.  
  803.         case SRE_OP_BRANCH:
  804.             /* alternation */
  805.             /* <BRANCH> <0=skip> code <JUMP> ... <NULL> */
  806.             TRACE(("|%p|%p|BRANCH\n", pattern, ptr));
  807.             lastmark = state->lastmark;
  808.             for (; pattern[0]; pattern += pattern[0]) {
  809.                 if (pattern[1] == SRE_OP_LITERAL &&
  810.                     (ptr >= end || (SRE_CODE) *ptr != pattern[2]))
  811.                     continue;
  812.                 if (pattern[1] == SRE_OP_IN &&
  813.                     (ptr >= end || !SRE_CHARSET(pattern + 3, (SRE_CODE) *ptr)))
  814.                     continue;
  815.                 state->ptr = ptr;
  816.                 i = SRE_MATCH(state, pattern + 1, level + 1);
  817.                 if (i)
  818.                     return i;
  819.                 if (state->lastmark > lastmark) {
  820.                     memset(
  821.                         state->mark + lastmark + 1, 0,
  822.                         (state->lastmark - lastmark) * sizeof(void*)
  823.                         );
  824.                     state->lastmark = lastmark;
  825.                 }
  826.             }
  827.             return 0;
  828.  
  829.         case SRE_OP_REPEAT_ONE:
  830.             /* match repeated sequence (maximizing regexp) */
  831.  
  832.             /* this operator only works if the repeated item is
  833.                exactly one character wide, and we're not already
  834.                collecting backtracking points.  for other cases,
  835.                use the MAX_REPEAT operator instead */
  836.  
  837.             /* <REPEAT_ONE> <skip> <1=min> <2=max> item <SUCCESS> tail */
  838.  
  839.             TRACE(("|%p|%p|REPEAT_ONE %d %d\n", pattern, ptr,
  840.                    pattern[1], pattern[2]));
  841.  
  842.             if (ptr + pattern[1] > end)
  843.                 return 0; /* cannot match */
  844.  
  845.             state->ptr = ptr;
  846.  
  847.             count = SRE_COUNT(state, pattern + 3, pattern[2], level + 1);
  848.             if (count < 0)
  849.                 return count;
  850.  
  851.             ptr += count;
  852.  
  853.             /* when we arrive here, count contains the number of
  854.                matches, and ptr points to the tail of the target
  855.                string.  check if the rest of the pattern matches,
  856.                and backtrack if not. */
  857.  
  858.             if (count < (int) pattern[1])
  859.                 return 0;
  860.  
  861.             if (pattern[pattern[0]] == SRE_OP_SUCCESS) {
  862.                 /* tail is empty.  we're finished */
  863.                 state->ptr = ptr;
  864.                 return 1;
  865.  
  866.             } else if (pattern[pattern[0]] == SRE_OP_LITERAL) {
  867.                 /* tail starts with a literal. skip positions where
  868.                    the rest of the pattern cannot possibly match */
  869.                 chr = pattern[pattern[0]+1];
  870.                 for (;;) {
  871.                     while (count >= (int) pattern[1] &&
  872.                            (ptr >= end || *ptr != chr)) {
  873.                         ptr--;
  874.                         count--;
  875.                     }
  876.                     if (count < (int) pattern[1])
  877.                         break;
  878.                     state->ptr = ptr;
  879.                     i = SRE_MATCH(state, pattern + pattern[0], level + 1);
  880.                     if (i)
  881.                         return i;
  882.                     ptr--;
  883.                     count--;
  884.                 }
  885.  
  886.             } else {
  887.                 /* general case */
  888.                 lastmark = state->lastmark;
  889.                 while (count >= (int) pattern[1]) {
  890.                     state->ptr = ptr;
  891.                     i = SRE_MATCH(state, pattern + pattern[0], level + 1);
  892.                     if (i)
  893.                         return i;
  894.                     ptr--;
  895.                     count--;
  896.                     if (state->lastmark > lastmark) {
  897.                         memset(
  898.                             state->mark + lastmark + 1, 0,
  899.                             (state->lastmark - lastmark) * sizeof(void*)
  900.                             );
  901.                         state->lastmark = lastmark;
  902.                     }
  903.                 }
  904.             }
  905.             return 0;
  906.  
  907.         case SRE_OP_REPEAT:
  908.             /* create repeat context.  all the hard work is done
  909.                by the UNTIL operator */
  910.             /* <REPEAT> <skip> <1=min> <2=max> item <UNTIL> tail */
  911.             TRACE(("|%p|%p|REPEAT %d %d\n", pattern, ptr,
  912.                    pattern[1], pattern[2]));
  913.  
  914.             rep.count = -1;
  915.             rep.pattern = pattern;
  916.  
  917.             /* install new repeat context */
  918.             rep.prev = state->repeat;
  919.             state->repeat = &rep;
  920.  
  921.             state->ptr = ptr;
  922.             i = SRE_MATCH(state, pattern + pattern[0], level + 1);
  923.  
  924.             state->repeat = rep.prev;
  925.  
  926.             return i;
  927.  
  928.         case SRE_OP_MAX_UNTIL:
  929.             /* maximizing repeat */
  930.             /* <REPEAT> <skip> <1=min> <2=max> item <MAX_UNTIL> tail */
  931.  
  932.             /* FIXME: we probably need to deal with zero-width
  933.                matches in here... */
  934.  
  935.             rp = state->repeat;
  936.             if (!rp)
  937.                 return SRE_ERROR_STATE;
  938.  
  939.             state->ptr = ptr;
  940.  
  941.             count = rp->count + 1;
  942.  
  943.             TRACE(("|%p|%p|MAX_UNTIL %d\n", pattern, ptr, count));
  944.  
  945.             if (count < rp->pattern[1]) {
  946.                 /* not enough matches */
  947.                 rp->count = count;
  948.                 /* RECURSIVE */
  949.                 i = SRE_MATCH(state, rp->pattern + 3, level + 1);
  950.                 if (i)
  951.                     return i;
  952.                 rp->count = count - 1;
  953.                 state->ptr = ptr;
  954.                 return 0;
  955.             }
  956.  
  957.             if (count < rp->pattern[2] || rp->pattern[2] == 65535) {
  958.                 /* we may have enough matches, but if we can
  959.                    match another item, do so */
  960.                 rp->count = count;
  961.                 lastmark = state->lastmark;
  962.                 i = mark_save(state, 0, lastmark);
  963.                 if (i < 0)
  964.                     return i;
  965.                 /* RECURSIVE */
  966.                 i = SRE_MATCH(state, rp->pattern + 3, level + 1);
  967.                 if (i)
  968.                     return i;
  969.                 i = mark_restore(state, 0, lastmark);
  970.                 if (i < 0)
  971.                     return i;
  972.                 rp->count = count - 1;
  973.                 state->ptr = ptr;
  974.             }
  975.  
  976.             /* cannot match more repeated items here.  make sure the
  977.                tail matches */
  978.             state->repeat = rp->prev;
  979.             i = SRE_MATCH(state, pattern, level + 1);
  980.             if (i)
  981.                 return i;
  982.             state->repeat = rp;
  983.             return 0;
  984.  
  985.         case SRE_OP_MIN_UNTIL:
  986.             /* minimizing repeat */
  987.             /* <REPEAT> <skip> <1=min> <2=max> item <MIN_UNTIL> tail */
  988.  
  989.             rp = state->repeat;
  990.             if (!rp)
  991.                 return SRE_ERROR_STATE;
  992.  
  993.             count = rp->count + 1;
  994.  
  995.             TRACE(("|%p|%p|MIN_UNTIL %d\n", pattern, ptr, count));
  996.  
  997.             state->ptr = ptr;
  998.  
  999.             if (count < rp->pattern[1]) {
  1000.                 /* not enough matches */
  1001.                 rp->count = count;
  1002.                 /* RECURSIVE */
  1003.                 i = SRE_MATCH(state, rp->pattern + 3, level + 1);
  1004.                 if (i)
  1005.                     return i;
  1006.                 rp->count = count-1;
  1007.                 state->ptr = ptr;
  1008.                 return 0;
  1009.             }
  1010.  
  1011.             /* see if the tail matches */
  1012.             state->repeat = rp->prev;
  1013.             i = SRE_MATCH(state, pattern, level + 1);
  1014.             if (i) {
  1015.                 /* free(rp); */
  1016.                 return i;
  1017.             }
  1018.             state->repeat = rp;
  1019.  
  1020.             if (count >= rp->pattern[2] && rp->pattern[2] != 65535)
  1021.                 return 0;
  1022.  
  1023.             rp->count = count;
  1024.             /* RECURSIVE */
  1025.             i = SRE_MATCH(state, rp->pattern + 3, level + 1);
  1026.             if (i)
  1027.                 return i;
  1028.             rp->count = count - 1;
  1029.             return 0;
  1030.  
  1031.         default:
  1032.             TRACE(("|%p|%p|UNKNOWN %d\n", pattern, ptr, pattern[-1]));
  1033.             return SRE_ERROR_ILLEGAL;
  1034.         }
  1035.     }
  1036.  
  1037.     /* shouldn't end up here */
  1038.     return SRE_ERROR_ILLEGAL;
  1039. }
  1040.  
  1041. LOCAL(int)
  1042. SRE_SEARCH(SRE_STATE* state, SRE_CODE* pattern)
  1043. {
  1044.     SRE_CHAR* ptr = state->start;
  1045.     SRE_CHAR* end = state->end;
  1046.     int status = 0;
  1047.     int prefix_len = 0;
  1048.     int prefix_skip;
  1049.     SRE_CODE* prefix = NULL;
  1050.     SRE_CODE* charset = NULL;
  1051.     SRE_CODE* overlap = NULL;
  1052.     int flags = 0;
  1053.  
  1054.     if (pattern[0] == SRE_OP_INFO) {
  1055.         /* optimization info block */
  1056.         /* <INFO> <1=skip> <2=flags> <3=min> <4=max> <5=prefix info>  */
  1057.  
  1058.         flags = pattern[2];
  1059.  
  1060.         if (pattern[3] > 0) {
  1061.             /* adjust end point (but make sure we leave at least one
  1062.                character in there, so literal search will work) */
  1063.             end -= pattern[3]-1;
  1064.             if (end <= ptr)
  1065.                 end = ptr+1;
  1066.         }
  1067.  
  1068.         if (flags & SRE_INFO_PREFIX) {
  1069.             /* pattern starts with a known prefix */
  1070.             /* <length> <skip> <prefix data> <overlap data> */
  1071.             prefix_len = pattern[5];
  1072.             prefix_skip = pattern[6];
  1073.             prefix = pattern + 7;
  1074.             overlap = prefix + prefix_len - 1;
  1075.         } else if (flags & SRE_INFO_CHARSET)
  1076.             /* pattern starts with a character from a known set */
  1077.             /* <charset> */
  1078.             charset = pattern + 5;
  1079.  
  1080.         pattern += 1 + pattern[1];
  1081.     }
  1082.  
  1083.     TRACE(("prefix = %p %d %d\n", prefix, prefix_len, prefix_skip));
  1084.     TRACE(("charset = %p\n", charset));
  1085.  
  1086. #if defined(USE_FAST_SEARCH)
  1087.     if (prefix_len > 1) {
  1088.         /* pattern starts with a known prefix.  use the overlap
  1089.            table to skip forward as fast as we possibly can */
  1090.         int i = 0;
  1091.         end = state->end;
  1092.         while (ptr < end) {
  1093.             for (;;) {
  1094.                 if ((SRE_CODE) ptr[0] != prefix[i]) {
  1095.                     if (!i)
  1096.                         break;
  1097.                     else
  1098.                         i = overlap[i];
  1099.                 } else {
  1100.                     if (++i == prefix_len) {
  1101.                         /* found a potential match */
  1102.                         TRACE(("|%p|%p|SEARCH SCAN\n", pattern, ptr));
  1103.                         state->start = ptr + 1 - prefix_len;
  1104.                         state->ptr = ptr + 1 - prefix_len + prefix_skip;
  1105.                         if (flags & SRE_INFO_LITERAL)
  1106.                             return 1; /* we got all of it */
  1107.                         status = SRE_MATCH(state, pattern + 2*prefix_skip, 1);
  1108.                         if (status != 0)
  1109.                             return status;
  1110.                         /* close but no cigar -- try again */
  1111.                         i = overlap[i];
  1112.                     }
  1113.                     break;
  1114.                 }
  1115.                 
  1116.             }
  1117.             ptr++;
  1118.         }
  1119.         return 0;
  1120.     }
  1121. #endif
  1122.  
  1123.     if (pattern[0] == SRE_OP_LITERAL) {
  1124.         /* pattern starts with a literal character.  this is used
  1125.            for short prefixes, and if fast search is disabled */
  1126.         SRE_CODE chr = pattern[1];
  1127.         end = state->end;
  1128.         for (;;) {
  1129.             while (ptr < end && (SRE_CODE) ptr[0] != chr)
  1130.                 ptr++;
  1131.             if (ptr == end)
  1132.                 return 0;
  1133.             TRACE(("|%p|%p|SEARCH LITERAL\n", pattern, ptr));
  1134.             state->start = ptr;
  1135.             state->ptr = ++ptr;
  1136.             status = SRE_MATCH(state, pattern + 2, 1);
  1137.             if (status != 0)
  1138.                 break;
  1139.         }
  1140.     } else if (charset) {
  1141.         /* pattern starts with a character from a known set */
  1142.         end = state->end;
  1143.         for (;;) {
  1144.             while (ptr < end && !SRE_CHARSET(charset, ptr[0]))
  1145.                 ptr++;
  1146.             if (ptr == end)
  1147.                 return 0;
  1148.             TRACE(("|%p|%p|SEARCH CHARSET\n", pattern, ptr));
  1149.             state->start = ptr;
  1150.             state->ptr = ptr;
  1151.             status = SRE_MATCH(state, pattern, 1);
  1152.             if (status != 0)
  1153.                 break;
  1154.             ptr++;
  1155.         }
  1156.     } else
  1157.         /* general case */
  1158.         while (ptr <= end) {
  1159.             TRACE(("|%p|%p|SEARCH\n", pattern, ptr));
  1160.             state->start = state->ptr = ptr++;
  1161.             status = SRE_MATCH(state, pattern, 1);
  1162.             if (status != 0)
  1163.                 break;
  1164.         }
  1165.  
  1166.     return status;
  1167. }
  1168.     
  1169.  
  1170. #if !defined(SRE_RECURSIVE)
  1171.  
  1172. /* -------------------------------------------------------------------- */
  1173. /* factories and destructors */
  1174.  
  1175. /* see sre.h for object declarations */
  1176.  
  1177. staticforward PyTypeObject Pattern_Type;
  1178. staticforward PyTypeObject Match_Type;
  1179. staticforward PyTypeObject Scanner_Type;
  1180.  
  1181. static PyObject *
  1182. _compile(PyObject* self_, PyObject* args)
  1183. {
  1184.     /* "compile" pattern descriptor to pattern object */
  1185.  
  1186.     PatternObject* self;
  1187.     int i, n;
  1188.  
  1189.     PyObject* pattern;
  1190.     int flags = 0;
  1191.     PyObject* code;
  1192.     int groups = 0;
  1193.     PyObject* groupindex = NULL;
  1194.     PyObject* indexgroup = NULL;
  1195.     if (!PyArg_ParseTuple(args, "OiO|iOO", &pattern, &flags, &code,
  1196.                           &groups, &groupindex, &indexgroup))
  1197.         return NULL;
  1198.  
  1199.     code = PySequence_Fast(code, "code argument must be a sequence");
  1200.     if (!code)
  1201.         return NULL;
  1202.  
  1203. #if PY_VERSION_HEX >= 0x01060000
  1204.     n = PySequence_Size(code);
  1205. #else
  1206.     n = PySequence_Length(code);
  1207. #endif
  1208.  
  1209.     self = PyObject_NEW_VAR(PatternObject, &Pattern_Type, 100*n);
  1210.     if (!self) {
  1211.         Py_DECREF(code);
  1212.         return NULL;
  1213.     }
  1214.  
  1215.     for (i = 0; i < n; i++) {
  1216.         PyObject *o = PySequence_Fast_GET_ITEM(code, i);
  1217.         self->code[i] = (SRE_CODE) PyInt_AsLong(o);
  1218.     }
  1219.  
  1220.     Py_DECREF(code);
  1221.  
  1222.     if (PyErr_Occurred())
  1223.         return NULL;
  1224.  
  1225.     Py_INCREF(pattern);
  1226.     self->pattern = pattern;
  1227.  
  1228.     self->flags = flags;
  1229.  
  1230.     self->groups = groups;
  1231.  
  1232.     Py_XINCREF(groupindex);
  1233.     self->groupindex = groupindex;
  1234.  
  1235.     Py_XINCREF(indexgroup);
  1236.     self->indexgroup = indexgroup;
  1237.  
  1238.     return (PyObject*) self;
  1239. }
  1240.  
  1241. static PyObject *
  1242. sre_codesize(PyObject* self, PyObject* args)
  1243. {
  1244.     return Py_BuildValue("i", sizeof(SRE_CODE));
  1245. }
  1246.  
  1247. static PyObject *
  1248. sre_getlower(PyObject* self, PyObject* args)
  1249. {
  1250.     int character, flags;
  1251.     if (!PyArg_ParseTuple(args, "ii", &character, &flags))
  1252.         return NULL;
  1253.     if (flags & SRE_FLAG_LOCALE)
  1254.         return Py_BuildValue("i", sre_lower_locale(character));
  1255. #if defined(HAVE_UNICODE)
  1256.     if (flags & SRE_FLAG_UNICODE)
  1257.         return Py_BuildValue("i", sre_lower_unicode(character));
  1258. #endif
  1259.     return Py_BuildValue("i", sre_lower(character));
  1260. }
  1261.  
  1262. LOCAL(void)
  1263. state_reset(SRE_STATE* state)
  1264. {
  1265.     int i;
  1266.  
  1267.     state->lastmark = 0;
  1268.  
  1269.     /* FIXME: dynamic! */
  1270.     for (i = 0; i < SRE_MARK_SIZE; i++)
  1271.         state->mark[i] = NULL;
  1272.  
  1273.     state->lastindex = -1;
  1274.  
  1275.     state->repeat = NULL;
  1276.  
  1277.     mark_fini(state);
  1278. }
  1279.  
  1280. LOCAL(PyObject*)
  1281. state_init(SRE_STATE* state, PatternObject* pattern, PyObject* string,
  1282.            int start, int end)
  1283. {
  1284.     /* prepare state object */
  1285.  
  1286.     PyBufferProcs *buffer;
  1287.     int size, bytes;
  1288.     void* ptr;
  1289.  
  1290.     memset(state, 0, sizeof(SRE_STATE));
  1291.  
  1292.     state->lastindex = -1;
  1293.  
  1294.     /* get pointer to string buffer */
  1295.     buffer = string->ob_type->tp_as_buffer;
  1296.     if (!buffer || !buffer->bf_getreadbuffer || !buffer->bf_getsegcount ||
  1297.         buffer->bf_getsegcount(string, NULL) != 1) {
  1298.         PyErr_SetString(PyExc_TypeError, "expected string or buffer");
  1299.         return NULL;
  1300.     }
  1301.  
  1302.     /* determine buffer size */
  1303.     bytes = buffer->bf_getreadbuffer(string, 0, &ptr);
  1304.     if (bytes < 0) {
  1305.         PyErr_SetString(PyExc_TypeError, "buffer has negative size");
  1306.         return NULL;
  1307.     }
  1308.  
  1309.     /* determine character size */
  1310.  
  1311. #if PY_VERSION_HEX >= 0x01060000
  1312.     size = PyObject_Size(string);
  1313. #else
  1314.     size = PyObject_Length(string);
  1315. #endif
  1316.  
  1317.     if (PyString_Check(string) || bytes == size)
  1318.         state->charsize = 1;
  1319. #if defined(HAVE_UNICODE)
  1320.     else if (bytes == (int) (size * sizeof(Py_UNICODE)))
  1321.         state->charsize = sizeof(Py_UNICODE);
  1322. #endif
  1323.     else {
  1324.         PyErr_SetString(PyExc_TypeError, "buffer size mismatch");
  1325.         return NULL;
  1326.     }
  1327.  
  1328.     /* adjust boundaries */
  1329.     if (start < 0)
  1330.         start = 0;
  1331.     else if (start > size)
  1332.         start = size;
  1333.  
  1334.     if (end < 0)
  1335.         end = 0;
  1336.     else if (end > size)
  1337.         end = size;
  1338.  
  1339.     state->beginning = ptr;
  1340.  
  1341.     state->start = (void*) ((char*) ptr + start * state->charsize);
  1342.     state->end = (void*) ((char*) ptr + end * state->charsize);
  1343.  
  1344.     Py_INCREF(string);
  1345.     state->string = string;
  1346.     state->pos = start;
  1347.     state->endpos = end;
  1348.  
  1349.     if (pattern->flags & SRE_FLAG_LOCALE)
  1350.         state->lower = sre_lower_locale;
  1351. #if defined(HAVE_UNICODE)
  1352.     else if (pattern->flags & SRE_FLAG_UNICODE)
  1353.         state->lower = sre_lower_unicode;
  1354. #endif
  1355.     else
  1356.         state->lower = sre_lower;
  1357.  
  1358.     return string;
  1359. }
  1360.  
  1361. LOCAL(void)
  1362. state_fini(SRE_STATE* state)
  1363. {
  1364.     Py_XDECREF(state->string);
  1365.     mark_fini(state);
  1366. }
  1367.  
  1368. LOCAL(PyObject*)
  1369. state_getslice(SRE_STATE* state, int index, PyObject* string)
  1370. {
  1371.     int i, j;
  1372.  
  1373.     index = (index - 1) * 2;
  1374.  
  1375.     if (string == Py_None || !state->mark[index] || !state->mark[index+1]) {
  1376.         i = j = 0;
  1377.     } else {
  1378.         i = ((char*)state->mark[index] - (char*)state->beginning) /
  1379.             state->charsize;
  1380.         j = ((char*)state->mark[index+1] - (char*)state->beginning) /
  1381.             state->charsize;
  1382.     }
  1383.  
  1384.     return PySequence_GetSlice(string, i, j);
  1385. }
  1386.  
  1387. static void
  1388. pattern_error(int status)
  1389. {
  1390.     switch (status) {
  1391.     case SRE_ERROR_RECURSION_LIMIT:
  1392.         PyErr_SetString(
  1393.             PyExc_RuntimeError,
  1394.             "maximum recursion limit exceeded"
  1395.             );
  1396.         break;
  1397.     case SRE_ERROR_MEMORY:
  1398.         PyErr_NoMemory();
  1399.         break;
  1400.     default:
  1401.         /* other error codes indicate compiler/engine bugs */
  1402.         PyErr_SetString(
  1403.             PyExc_RuntimeError,
  1404.             "internal error in regular expression engine"
  1405.             );
  1406.     }
  1407. }
  1408.  
  1409. static PyObject*
  1410. pattern_new_match(PatternObject* pattern, SRE_STATE* state, int status)
  1411. {
  1412.     /* create match object (from state object) */
  1413.  
  1414.     MatchObject* match;
  1415.     int i, j;
  1416.     char* base;
  1417.     int n;
  1418.  
  1419.     if (status > 0) {
  1420.  
  1421.         /* create match object (with room for extra group marks) */
  1422.         match = PyObject_NEW_VAR(MatchObject, &Match_Type,
  1423.                                  2*(pattern->groups+1));
  1424.         if (!match)
  1425.             return NULL;
  1426.  
  1427.         Py_INCREF(pattern);
  1428.         match->pattern = pattern;
  1429.  
  1430.         Py_INCREF(state->string);
  1431.         match->string = state->string;
  1432.  
  1433.         match->regs = NULL;
  1434.         match->groups = pattern->groups+1;
  1435.  
  1436.         /* fill in group slices */
  1437.  
  1438.         base = (char*) state->beginning;
  1439.         n = state->charsize;
  1440.  
  1441.         match->mark[0] = ((char*) state->start - base) / n;
  1442.         match->mark[1] = ((char*) state->ptr - base) / n;
  1443.  
  1444.         for (i = j = 0; i < pattern->groups; i++, j+=2)
  1445.             if (j+1 <= state->lastmark && state->mark[j] && state->mark[j+1]) {
  1446.                 match->mark[j+2] = ((char*) state->mark[j] - base) / n;
  1447.                 match->mark[j+3] = ((char*) state->mark[j+1] - base) / n;
  1448.             } else
  1449.                 match->mark[j+2] = match->mark[j+3] = -1; /* undefined */
  1450.  
  1451.         match->pos = state->pos;
  1452.         match->endpos = state->endpos;
  1453.  
  1454.         match->lastindex = state->lastindex;
  1455.  
  1456.         return (PyObject*) match;
  1457.  
  1458.     } else if (status == 0) {
  1459.  
  1460.         /* no match */
  1461.         Py_INCREF(Py_None);
  1462.         return Py_None;
  1463.  
  1464.     }
  1465.  
  1466.     /* internal error */
  1467.     pattern_error(status);
  1468.     return NULL;
  1469. }
  1470.  
  1471. static PyObject*
  1472. pattern_scanner(PatternObject* pattern, PyObject* args)
  1473. {
  1474.     /* create search state object */
  1475.  
  1476.     ScannerObject* self;
  1477.  
  1478.     PyObject* string;
  1479.     int start = 0;
  1480.     int end = INT_MAX;
  1481.     if (!PyArg_ParseTuple(args, "O|ii:scanner", &string, &start, &end))
  1482.         return NULL;
  1483.  
  1484.     /* create scanner object */
  1485.     self = PyObject_NEW(ScannerObject, &Scanner_Type);
  1486.     if (!self)
  1487.         return NULL;
  1488.  
  1489.     string = state_init(&self->state, pattern, string, start, end);
  1490.     if (!string) {
  1491.         PyObject_Del(self);
  1492.         return NULL;
  1493.     }
  1494.  
  1495.     Py_INCREF(pattern);
  1496.     self->pattern = (PyObject*) pattern;
  1497.  
  1498.     return (PyObject*) self;
  1499. }
  1500.  
  1501. static void
  1502. pattern_dealloc(PatternObject* self)
  1503. {
  1504.     Py_XDECREF(self->pattern);
  1505.     Py_XDECREF(self->groupindex);
  1506.     PyObject_DEL(self);
  1507. }
  1508.  
  1509. static PyObject*
  1510. pattern_match(PatternObject* self, PyObject* args)
  1511. {
  1512.     SRE_STATE state;
  1513.     int status;
  1514.  
  1515.     PyObject* string;
  1516.     int start = 0;
  1517.     int end = INT_MAX;
  1518.     if (!PyArg_ParseTuple(args, "O|ii:match", &string, &start, &end))
  1519.         return NULL;
  1520.  
  1521.     string = state_init(&state, self, string, start, end);
  1522.     if (!string)
  1523.         return NULL;
  1524.  
  1525.     state.ptr = state.start;
  1526.  
  1527.     TRACE(("|%p|%p|MATCH\n", PatternObject_GetCode(self), state.ptr));
  1528.  
  1529.     if (state.charsize == 1) {
  1530.         status = sre_match(&state, PatternObject_GetCode(self), 1);
  1531.     } else {
  1532. #if defined(HAVE_UNICODE)
  1533.         status = sre_umatch(&state, PatternObject_GetCode(self), 1);
  1534. #endif
  1535.     }
  1536.  
  1537.     TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr));
  1538.  
  1539.     state_fini(&state);
  1540.  
  1541.     return pattern_new_match(self, &state, status);
  1542. }
  1543.  
  1544. static PyObject*
  1545. pattern_search(PatternObject* self, PyObject* args)
  1546. {
  1547.     SRE_STATE state;
  1548.     int status;
  1549.  
  1550.     PyObject* string;
  1551.     int start = 0;
  1552.     int end = INT_MAX;
  1553.     if (!PyArg_ParseTuple(args, "O|ii:search", &string, &start, &end))
  1554.         return NULL;
  1555.  
  1556.     string = state_init(&state, self, string, start, end);
  1557.     if (!string)
  1558.         return NULL;
  1559.  
  1560.     TRACE(("|%p|%p|SEARCH\n", PatternObject_GetCode(self), state.ptr));
  1561.  
  1562.     if (state.charsize == 1) {
  1563.         status = sre_search(&state, PatternObject_GetCode(self));
  1564.     } else {
  1565. #if defined(HAVE_UNICODE)
  1566.         status = sre_usearch(&state, PatternObject_GetCode(self));
  1567. #endif
  1568.     }
  1569.  
  1570.     TRACE(("|%p|%p|END\n", PatternObject_GetCode(self), state.ptr));
  1571.  
  1572.     state_fini(&state);
  1573.  
  1574.     return pattern_new_match(self, &state, status);
  1575. }
  1576.  
  1577. static PyObject*
  1578. call(char* function, PyObject* args)
  1579. {
  1580.     PyObject* name;
  1581.     PyObject* module;
  1582.     PyObject* func;
  1583.     PyObject* result;
  1584.  
  1585.     name = PyString_FromString(MODULE);
  1586.     if (!name)
  1587.         return NULL;
  1588.     module = PyImport_Import(name);
  1589.     Py_DECREF(name);
  1590.     if (!module)
  1591.         return NULL;
  1592.     func = PyObject_GetAttrString(module, function);
  1593.     Py_DECREF(module);
  1594.     if (!func)
  1595.         return NULL;
  1596.     result = PyObject_CallObject(func, args);
  1597.     Py_DECREF(func);
  1598.     Py_DECREF(args);
  1599.     return result;
  1600. }
  1601.  
  1602. static PyObject*
  1603. pattern_sub(PatternObject* self, PyObject* args)
  1604. {
  1605.     PyObject* template;
  1606.     PyObject* string;
  1607.     PyObject* count = Py_False; /* zero */
  1608.     if (!PyArg_ParseTuple(args, "OO|O:sub", &template, &string, &count))
  1609.         return NULL;
  1610.  
  1611.     /* delegate to Python code */
  1612.     return call("_sub", Py_BuildValue("OOOO", self, template, string, count));
  1613. }
  1614.  
  1615. static PyObject*
  1616. pattern_subn(PatternObject* self, PyObject* args)
  1617. {
  1618.     PyObject* template;
  1619.     PyObject* string;
  1620.     PyObject* count = Py_False; /* zero */
  1621.     if (!PyArg_ParseTuple(args, "OO|O:subn", &template, &string, &count))
  1622.         return NULL;
  1623.  
  1624.     /* delegate to Python code */
  1625.     return call("_subn", Py_BuildValue("OOOO", self, template, string, count));
  1626. }
  1627.  
  1628. static PyObject*
  1629. pattern_split(PatternObject* self, PyObject* args)
  1630. {
  1631.     PyObject* string;
  1632.     PyObject* maxsplit = Py_False; /* zero */
  1633.     if (!PyArg_ParseTuple(args, "O|O:split", &string, &maxsplit))
  1634.         return NULL;
  1635.  
  1636.     /* delegate to Python code */
  1637.     return call("_split", Py_BuildValue("OOO", self, string, maxsplit));
  1638. }
  1639.  
  1640. static PyObject*
  1641. pattern_findall(PatternObject* self, PyObject* args)
  1642. {
  1643.     SRE_STATE state;
  1644.     PyObject* list;
  1645.     int status;
  1646.     int i;
  1647.  
  1648.     PyObject* string;
  1649.     int start = 0;
  1650.     int end = INT_MAX;
  1651.     if (!PyArg_ParseTuple(args, "O|ii:findall", &string, &start, &end))
  1652.         return NULL;
  1653.  
  1654.     string = state_init(&state, self, string, start, end);
  1655.     if (!string)
  1656.         return NULL;
  1657.  
  1658.     list = PyList_New(0);
  1659.  
  1660.     while (state.start <= state.end) {
  1661.  
  1662.         PyObject* item;
  1663.         
  1664.         state.ptr = state.start;
  1665.  
  1666.         if (state.charsize == 1) {
  1667.             status = sre_search(&state, PatternObject_GetCode(self));
  1668.         } else {
  1669. #if defined(HAVE_UNICODE)
  1670.             status = sre_usearch(&state, PatternObject_GetCode(self));
  1671. #endif
  1672.         }
  1673.  
  1674.         if (status > 0) {
  1675.  
  1676.             /* don't bother to build a match object */
  1677.             switch (self->groups) {
  1678.             case 0:
  1679.                 item = PySequence_GetSlice(
  1680.                     string,
  1681.                     ((char*) state.start - (char*) state.beginning) /
  1682.                     state.charsize,
  1683.                     ((char*) state.ptr - (char*) state.beginning) /
  1684.                     state.charsize);
  1685.                 if (!item)
  1686.                     goto error;
  1687.                 break;
  1688.             case 1:
  1689.                 item = state_getslice(&state, 1, string);
  1690.                 if (!item)
  1691.                     goto error;
  1692.                 break;
  1693.             default:
  1694.                 item = PyTuple_New(self->groups);
  1695.                 if (!item)
  1696.                     goto error;
  1697.                 for (i = 0; i < self->groups; i++) {
  1698.                     PyObject* o = state_getslice(&state, i+1, string);
  1699.                     if (!o) {
  1700.                         Py_DECREF(item);
  1701.                         goto error;
  1702.                     }
  1703.                     PyTuple_SET_ITEM(item, i, o);
  1704.                 }
  1705.                 break;
  1706.             }
  1707.  
  1708.             status = PyList_Append(list, item);
  1709.             Py_DECREF(item);
  1710.  
  1711.             if (status < 0)
  1712.                 goto error;
  1713.  
  1714.             if (state.ptr == state.start)
  1715.                 state.start = (void*) ((char*) state.ptr + state.charsize);
  1716.             else
  1717.                 state.start = state.ptr;
  1718.  
  1719.         } else {
  1720.  
  1721.             if (status == 0)
  1722.                 break;
  1723.  
  1724.             pattern_error(status);
  1725.             goto error;
  1726.  
  1727.         }
  1728.     }
  1729.  
  1730.     state_fini(&state);
  1731.     return list;
  1732.  
  1733. error:
  1734.     Py_DECREF(list);
  1735.     state_fini(&state);
  1736.     return NULL;
  1737.     
  1738. }
  1739.  
  1740. static PyMethodDef pattern_methods[] = {
  1741.     {"match", (PyCFunction) pattern_match, 1},
  1742.     {"search", (PyCFunction) pattern_search, 1},
  1743.     {"sub", (PyCFunction) pattern_sub, 1},
  1744.     {"subn", (PyCFunction) pattern_subn, 1},
  1745.     {"split", (PyCFunction) pattern_split, 1},
  1746.     {"findall", (PyCFunction) pattern_findall, 1},
  1747.     /* experimental */
  1748.     {"scanner", (PyCFunction) pattern_scanner, 1},
  1749.     {NULL, NULL}
  1750. };
  1751.  
  1752. static PyObject*  
  1753. pattern_getattr(PatternObject* self, char* name)
  1754. {
  1755.     PyObject* res;
  1756.  
  1757.     res = Py_FindMethod(pattern_methods, (PyObject*) self, name);
  1758.  
  1759.     if (res)
  1760.         return res;
  1761.  
  1762.     PyErr_Clear();
  1763.  
  1764.     /* attributes */
  1765.     if (!strcmp(name, "pattern")) {
  1766.         Py_INCREF(self->pattern);
  1767.         return self->pattern;
  1768.     }
  1769.  
  1770.     if (!strcmp(name, "flags"))
  1771.         return Py_BuildValue("i", self->flags);
  1772.  
  1773.     if (!strcmp(name, "groups"))
  1774.         return Py_BuildValue("i", self->groups);
  1775.  
  1776.     if (!strcmp(name, "groupindex") && self->groupindex) {
  1777.         Py_INCREF(self->groupindex);
  1778.         return self->groupindex;
  1779.     }
  1780.  
  1781.     PyErr_SetString(PyExc_AttributeError, name);
  1782.     return NULL;
  1783. }
  1784.  
  1785. statichere PyTypeObject Pattern_Type = {
  1786.     PyObject_HEAD_INIT(NULL)
  1787.     0, "SRE_Pattern",
  1788.     sizeof(PatternObject), sizeof(SRE_CODE),
  1789.     (destructor)pattern_dealloc, /*tp_dealloc*/
  1790.     0, /*tp_print*/
  1791.     (getattrfunc)pattern_getattr /*tp_getattr*/
  1792. };
  1793.  
  1794. /* -------------------------------------------------------------------- */
  1795. /* match methods */
  1796.  
  1797. static void
  1798. match_dealloc(MatchObject* self)
  1799. {
  1800.     Py_XDECREF(self->regs);
  1801.     Py_XDECREF(self->string);
  1802.     Py_DECREF(self->pattern);
  1803.     PyObject_DEL(self);
  1804. }
  1805.  
  1806. static PyObject*
  1807. match_getslice_by_index(MatchObject* self, int index, PyObject* def)
  1808. {
  1809.     if (index < 0 || index >= self->groups) {
  1810.         /* raise IndexError if we were given a bad group number */
  1811.         PyErr_SetString(
  1812.             PyExc_IndexError,
  1813.             "no such group"
  1814.             );
  1815.         return NULL;
  1816.     }
  1817.  
  1818.     index *= 2;
  1819.  
  1820.     if (self->string == Py_None || self->mark[index] < 0) {
  1821.         /* return default value if the string or group is undefined */
  1822.         Py_INCREF(def);
  1823.         return def;
  1824.     }
  1825.  
  1826.     return PySequence_GetSlice(
  1827.         self->string, self->mark[index], self->mark[index+1]
  1828.         );
  1829. }
  1830.  
  1831. static int
  1832. match_getindex(MatchObject* self, PyObject* index)
  1833. {
  1834.     int i;
  1835.  
  1836.     if (PyInt_Check(index))
  1837.         return (int) PyInt_AS_LONG(index);
  1838.  
  1839.     i = -1;
  1840.  
  1841.     if (self->pattern->groupindex) {
  1842.         index = PyObject_GetItem(self->pattern->groupindex, index);
  1843.         if (index) {
  1844.             if (PyInt_Check(index))
  1845.                 i = (int) PyInt_AS_LONG(index);
  1846.             Py_DECREF(index);
  1847.         } else
  1848.             PyErr_Clear();
  1849.     }
  1850.  
  1851.     return i;
  1852. }
  1853.  
  1854. static PyObject*
  1855. match_getslice(MatchObject* self, PyObject* index, PyObject* def)
  1856. {
  1857.     return match_getslice_by_index(self, match_getindex(self, index), def);
  1858. }
  1859.  
  1860. static PyObject*
  1861. match_group(MatchObject* self, PyObject* args)
  1862. {
  1863.     PyObject* result;
  1864.     int i, size;
  1865.  
  1866.     size = PyTuple_GET_SIZE(args);
  1867.  
  1868.     switch (size) {
  1869.     case 0:
  1870.         result = match_getslice(self, Py_False, Py_None);
  1871.         break;
  1872.     case 1:
  1873.         result = match_getslice(self, PyTuple_GET_ITEM(args, 0), Py_None);
  1874.         break;
  1875.     default:
  1876.         /* fetch multiple items */
  1877.         result = PyTuple_New(size);
  1878.         if (!result)
  1879.             return NULL;
  1880.         for (i = 0; i < size; i++) {
  1881.             PyObject* item = match_getslice(
  1882.                 self, PyTuple_GET_ITEM(args, i), Py_None
  1883.                 );
  1884.             if (!item) {
  1885.                 Py_DECREF(result);
  1886.                 return NULL;
  1887.             }
  1888.             PyTuple_SET_ITEM(result, i, item);
  1889.         }
  1890.         break;
  1891.     }
  1892.     return result;
  1893. }
  1894.  
  1895. static PyObject*
  1896. match_groups(MatchObject* self, PyObject* args)
  1897. {
  1898.     PyObject* result;
  1899.     int index;
  1900.  
  1901.     PyObject* def = Py_None;
  1902.     if (!PyArg_ParseTuple(args, "|O:groups", &def))
  1903.         return NULL;
  1904.  
  1905.     result = PyTuple_New(self->groups-1);
  1906.     if (!result)
  1907.         return NULL;
  1908.  
  1909.     for (index = 1; index < self->groups; index++) {
  1910.         PyObject* item;
  1911.         item = match_getslice_by_index(self, index, def);
  1912.         if (!item) {
  1913.             Py_DECREF(result);
  1914.             return NULL;
  1915.         }
  1916.         PyTuple_SET_ITEM(result, index-1, item);
  1917.     }
  1918.  
  1919.     return result;
  1920. }
  1921.  
  1922. static PyObject*
  1923. match_groupdict(MatchObject* self, PyObject* args)
  1924. {
  1925.     PyObject* result;
  1926.     PyObject* keys;
  1927.     int index;
  1928.  
  1929.     PyObject* def = Py_None;
  1930.     if (!PyArg_ParseTuple(args, "|O:groupdict", &def))
  1931.         return NULL;
  1932.  
  1933.     result = PyDict_New();
  1934.     if (!result || !self->pattern->groupindex)
  1935.         return result;
  1936.  
  1937.     keys = PyMapping_Keys(self->pattern->groupindex);
  1938.     if (!keys) {
  1939.         Py_DECREF(result);
  1940.         return NULL;
  1941.     }
  1942.  
  1943.     for (index = 0; index < PyList_GET_SIZE(keys); index++) {
  1944.         PyObject* key;
  1945.         PyObject* item;
  1946.         key = PyList_GET_ITEM(keys, index);
  1947.         if (!key) {
  1948.             Py_DECREF(keys);
  1949.             Py_DECREF(result);
  1950.             return NULL;
  1951.         }
  1952.         item = match_getslice(self, key, def);
  1953.         if (!item) {
  1954.             Py_DECREF(key);
  1955.             Py_DECREF(keys);
  1956.             Py_DECREF(result);
  1957.             return NULL;
  1958.         }
  1959.         /* FIXME: <fl> this can fail, right? */
  1960.         PyDict_SetItem(result, key, item);
  1961.     }
  1962.  
  1963.     Py_DECREF(keys);
  1964.  
  1965.     return result;
  1966. }
  1967.  
  1968. static PyObject*
  1969. match_start(MatchObject* self, PyObject* args)
  1970. {
  1971.     int index;
  1972.  
  1973.     PyObject* index_ = Py_False; /* zero */
  1974.     if (!PyArg_ParseTuple(args, "|O:start", &index_))
  1975.         return NULL;
  1976.  
  1977.     index = match_getindex(self, index_);
  1978.  
  1979.     if (index < 0 || index >= self->groups) {
  1980.         PyErr_SetString(
  1981.             PyExc_IndexError,
  1982.             "no such group"
  1983.             );
  1984.         return NULL;
  1985.     }
  1986.  
  1987.     /* mark is -1 if group is undefined */
  1988.     return Py_BuildValue("i", self->mark[index*2]);
  1989. }
  1990.  
  1991. static PyObject*
  1992. match_end(MatchObject* self, PyObject* args)
  1993. {
  1994.     int index;
  1995.  
  1996.     PyObject* index_ = Py_False; /* zero */
  1997.     if (!PyArg_ParseTuple(args, "|O:end", &index_))
  1998.         return NULL;
  1999.  
  2000.     index = match_getindex(self, index_);
  2001.  
  2002.     if (index < 0 || index >= self->groups) {
  2003.         PyErr_SetString(
  2004.             PyExc_IndexError,
  2005.             "no such group"
  2006.             );
  2007.         return NULL;
  2008.     }
  2009.  
  2010.     /* mark is -1 if group is undefined */
  2011.     return Py_BuildValue("i", self->mark[index*2+1]);
  2012. }
  2013.  
  2014. LOCAL(PyObject*)
  2015. _pair(int i1, int i2)
  2016. {
  2017.     PyObject* pair;
  2018.     PyObject* item;
  2019.  
  2020.     pair = PyTuple_New(2);
  2021.     if (!pair)
  2022.         return NULL;
  2023.  
  2024.     item = PyInt_FromLong(i1);
  2025.     if (!item)
  2026.         goto error;
  2027.     PyTuple_SET_ITEM(pair, 0, item);
  2028.  
  2029.     item = PyInt_FromLong(i2);
  2030.     if (!item)
  2031.         goto error;
  2032.     PyTuple_SET_ITEM(pair, 1, item);
  2033.  
  2034.     return pair;
  2035.  
  2036.   error:
  2037.     Py_DECREF(pair);
  2038.     return NULL;
  2039. }
  2040.  
  2041. static PyObject*
  2042. match_span(MatchObject* self, PyObject* args)
  2043. {
  2044.     int index;
  2045.  
  2046.     PyObject* index_ = Py_False; /* zero */
  2047.     if (!PyArg_ParseTuple(args, "|O:span", &index_))
  2048.         return NULL;
  2049.  
  2050.     index = match_getindex(self, index_);
  2051.  
  2052.     if (index < 0 || index >= self->groups) {
  2053.         PyErr_SetString(
  2054.             PyExc_IndexError,
  2055.             "no such group"
  2056.             );
  2057.         return NULL;
  2058.     }
  2059.  
  2060.     /* marks are -1 if group is undefined */
  2061.     return _pair(self->mark[index*2], self->mark[index*2+1]);
  2062. }
  2063.  
  2064. static PyObject*
  2065. match_regs(MatchObject* self)
  2066. {
  2067.     PyObject* regs;
  2068.     PyObject* item;
  2069.     int index;
  2070.  
  2071.     regs = PyTuple_New(self->groups);
  2072.     if (!regs)
  2073.         return NULL;
  2074.  
  2075.     for (index = 0; index < self->groups; index++) {
  2076.         item = _pair(self->mark[index*2], self->mark[index*2+1]);
  2077.         if (!item) {
  2078.             Py_DECREF(regs);
  2079.             return NULL;
  2080.         }
  2081.         PyTuple_SET_ITEM(regs, index, item);
  2082.     }
  2083.  
  2084.     Py_INCREF(regs);
  2085.     self->regs = regs;
  2086.  
  2087.     return regs;
  2088. }
  2089.  
  2090. static PyMethodDef match_methods[] = {
  2091.     {"group", (PyCFunction) match_group, 1},
  2092.     {"start", (PyCFunction) match_start, 1},
  2093.     {"end", (PyCFunction) match_end, 1},
  2094.     {"span", (PyCFunction) match_span, 1},
  2095.     {"groups", (PyCFunction) match_groups, 1},
  2096.     {"groupdict", (PyCFunction) match_groupdict, 1},
  2097.     {NULL, NULL}
  2098. };
  2099.  
  2100. static PyObject*  
  2101. match_getattr(MatchObject* self, char* name)
  2102. {
  2103.     PyObject* res;
  2104.  
  2105.     res = Py_FindMethod(match_methods, (PyObject*) self, name);
  2106.     if (res)
  2107.         return res;
  2108.  
  2109.     PyErr_Clear();
  2110.  
  2111.     if (!strcmp(name, "lastindex")) {
  2112.         if (self->lastindex >= 0)
  2113.             return Py_BuildValue("i", self->lastindex);
  2114.         Py_INCREF(Py_None);
  2115.         return Py_None;
  2116.     }
  2117.  
  2118.     if (!strcmp(name, "lastgroup")) {
  2119.         if (self->pattern->indexgroup && self->lastindex >= 0) {
  2120.             PyObject* result = PySequence_GetItem(
  2121.                 self->pattern->indexgroup, self->lastindex
  2122.                 );
  2123.             if (result)
  2124.                 return result;
  2125.             PyErr_Clear();
  2126.         }
  2127.         Py_INCREF(Py_None);
  2128.         return Py_None;
  2129.     }
  2130.  
  2131.     if (!strcmp(name, "string")) {
  2132.         if (self->string) {
  2133.             Py_INCREF(self->string);
  2134.             return self->string;
  2135.         } else {
  2136.             Py_INCREF(Py_None);
  2137.             return Py_None;
  2138.         }
  2139.     }
  2140.  
  2141.     if (!strcmp(name, "regs")) {
  2142.         if (self->regs) {
  2143.             Py_INCREF(self->regs);
  2144.             return self->regs;
  2145.         } else
  2146.             return match_regs(self);
  2147.     }
  2148.  
  2149.     if (!strcmp(name, "re")) {
  2150.         Py_INCREF(self->pattern);
  2151.         return (PyObject*) self->pattern;
  2152.     }
  2153.  
  2154.     if (!strcmp(name, "pos"))
  2155.         return Py_BuildValue("i", self->pos);
  2156.  
  2157.     if (!strcmp(name, "endpos"))
  2158.         return Py_BuildValue("i", self->endpos);
  2159.  
  2160.     PyErr_SetString(PyExc_AttributeError, name);
  2161.     return NULL;
  2162. }
  2163.  
  2164. /* FIXME: implement setattr("string", None) as a special case (to
  2165.    detach the associated string, if any */
  2166.  
  2167. statichere PyTypeObject Match_Type = {
  2168.     PyObject_HEAD_INIT(NULL)
  2169.     0, "SRE_Match",
  2170.     sizeof(MatchObject), sizeof(int),
  2171.     (destructor)match_dealloc, /*tp_dealloc*/
  2172.     0, /*tp_print*/
  2173.     (getattrfunc)match_getattr /*tp_getattr*/
  2174. };
  2175.  
  2176. /* -------------------------------------------------------------------- */
  2177. /* scanner methods (experimental) */
  2178.  
  2179. static void
  2180. scanner_dealloc(ScannerObject* self)
  2181. {
  2182.     state_fini(&self->state);
  2183.     Py_DECREF(self->pattern);
  2184.     PyObject_DEL(self);
  2185. }
  2186.  
  2187. static PyObject*
  2188. scanner_match(ScannerObject* self, PyObject* args)
  2189. {
  2190.     SRE_STATE* state = &self->state;
  2191.     PyObject* match;
  2192.     int status;
  2193.  
  2194.     state_reset(state);
  2195.  
  2196.     state->ptr = state->start;
  2197.  
  2198.     if (state->charsize == 1) {
  2199.         status = sre_match(state, PatternObject_GetCode(self->pattern), 1);
  2200.     } else {
  2201. #if defined(HAVE_UNICODE)
  2202.         status = sre_umatch(state, PatternObject_GetCode(self->pattern), 1);
  2203. #endif
  2204.     }
  2205.  
  2206.     match = pattern_new_match((PatternObject*) self->pattern,
  2207.                                state, status);
  2208.  
  2209.     if (status == 0 || state->ptr == state->start)
  2210.         state->start = (void*) ((char*) state->ptr + state->charsize);
  2211.     else
  2212.         state->start = state->ptr;
  2213.  
  2214.     return match;
  2215. }
  2216.  
  2217.  
  2218. static PyObject*
  2219. scanner_search(ScannerObject* self, PyObject* args)
  2220. {
  2221.     SRE_STATE* state = &self->state;
  2222.     PyObject* match;
  2223.     int status;
  2224.  
  2225.     state_reset(state);
  2226.  
  2227.     state->ptr = state->start;
  2228.  
  2229.     if (state->charsize == 1) {
  2230.         status = sre_search(state, PatternObject_GetCode(self->pattern));
  2231.     } else {
  2232. #if defined(HAVE_UNICODE)
  2233.         status = sre_usearch(state, PatternObject_GetCode(self->pattern));
  2234. #endif
  2235.     }
  2236.  
  2237.     match = pattern_new_match((PatternObject*) self->pattern,
  2238.                                state, status);
  2239.  
  2240.     if (status == 0 || state->ptr == state->start)
  2241.         state->start = (void*) ((char*) state->ptr + state->charsize);
  2242.     else
  2243.         state->start = state->ptr;
  2244.  
  2245.     return match;
  2246. }
  2247.  
  2248. static PyMethodDef scanner_methods[] = {
  2249.     {"match", (PyCFunction) scanner_match, 0},
  2250.     {"search", (PyCFunction) scanner_search, 0},
  2251.     {NULL, NULL}
  2252. };
  2253.  
  2254. static PyObject*  
  2255. scanner_getattr(ScannerObject* self, char* name)
  2256. {
  2257.     PyObject* res;
  2258.  
  2259.     res = Py_FindMethod(scanner_methods, (PyObject*) self, name);
  2260.     if (res)
  2261.         return res;
  2262.  
  2263.     PyErr_Clear();
  2264.  
  2265.     /* attributes */
  2266.     if (!strcmp(name, "pattern")) {
  2267.         Py_INCREF(self->pattern);
  2268.         return self->pattern;
  2269.     }
  2270.  
  2271.     PyErr_SetString(PyExc_AttributeError, name);
  2272.     return NULL;
  2273. }
  2274.  
  2275. statichere PyTypeObject Scanner_Type = {
  2276.     PyObject_HEAD_INIT(NULL)
  2277.     0, "SRE_Scanner",
  2278.     sizeof(ScannerObject), 0,
  2279.     (destructor)scanner_dealloc, /*tp_dealloc*/
  2280.     0, /*tp_print*/
  2281.     (getattrfunc)scanner_getattr, /*tp_getattr*/
  2282. };
  2283.  
  2284. static PyMethodDef _functions[] = {
  2285.     {"compile", _compile, 1},
  2286.     {"getcodesize", sre_codesize, 1},
  2287.     {"getlower", sre_getlower, 1},
  2288.     {NULL, NULL}
  2289. };
  2290.  
  2291. void
  2292. #if defined(WIN32)
  2293. __declspec(dllexport)
  2294. #endif
  2295. init_sre(void)
  2296. {
  2297.     /* Patch object types */
  2298.     Pattern_Type.ob_type = Match_Type.ob_type =
  2299.         Scanner_Type.ob_type = &PyType_Type;
  2300.  
  2301.     Py_InitModule("_" MODULE, _functions);
  2302. }
  2303.  
  2304. #endif /* !defined(SRE_RECURSIVE) */
  2305.